package com.rtx.edi.platform.structure.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import org.apache.poi.ss.usermodel.DataValidation;
import org.apache.poi.ss.usermodel.DataValidationConstraint;
import org.apache.poi.ss.usermodel.DataValidationHelper;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFDataValidationConstraint;
import org.apache.poi.xssf.usermodel.XSSFDataValidationHelper;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rtx.api.utils.FastJsonUtils;
import com.rtx.edi.model.api.dto.PlApiMappingDTO;
import com.rtx.edi.model.api.dto.PlApiMappingStructureDTO;
import com.rtx.edi.model.api.po.PlApiMapping;
import com.rtx.edi.model.api.po.PlApiMappingStructure;
import com.rtx.edi.model.apibaseinfo.po.PlApibaseinfo;
import com.rtx.edi.platform.baseinfo.mapper.PlApibaseinfoMapper;
import com.rtx.edi.platform.mapping.mapper.PlApiMappingMapper;
import com.rtx.edi.platform.structure.mapper.PlApiMappingStructureMapper;
import com.rtx.edi.platform.structure.service.PlApiMappingStructureService;

@Service
public class PlApiMappingStructureServiceImpl  extends ServiceImpl<PlApiMappingStructureMapper, PlApiMappingStructure> implements PlApiMappingStructureService {

	Logger log = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	PlApibaseinfoMapper plApibaseinfoMapper;
	
	@Autowired
	PlApiMappingMapper plApiMappingMapper;
	
	



	@Override
	public Map<String, Object> selectPlApiMappingStructureDetail(PlApiMappingStructureDTO dto) {
		
		Map<String,Object> res = new HashMap<String, Object>();
		PlApiMapping mappingPo = plApiMappingMapper.selectById(dto.getApiMappingId());
		long sApi = mappingPo.getSourceApiId();
		long tApi = mappingPo.getTargetApiId();
		PlApibaseinfo sapi = plApibaseinfoMapper.selectById(sApi);
		PlApibaseinfo tapi = plApibaseinfoMapper.selectById(tApi);
		
		String activeTarget = mappingPo.getActiveTarget();
		if("table".equals(activeTarget)) {
			String targetTemplate = getTargetTemplateForMysql(tapi);
			tapi.setApiRequestTemplate(targetTemplate);
			LambdaUpdateWrapper<PlApibaseinfo> uw = Wrappers.lambdaUpdate();
			uw.eq(PlApibaseinfo::getId, tapi.getId()).set(PlApibaseinfo::getApiRequestTemplate, targetTemplate);
			plApibaseinfoMapper.update(null, uw);
		}
		
		res.put("sTemplate", sapi.getApiRequestTemplate());
		res.put("tTemplate", tapi.getApiRequestTemplate());
		
		List<Map<String,String>> sSelectorList = new ArrayList<Map<String,String>>();
		List<Map<String, String>> sJsonList = FastJsonUtils.getFormatJSON(sapi.getApiRequestTemplate());
		for(Map<String,String> sJson:sJsonList) {
			if(!StringUtils.hasLength(sJson.get("fieldType"))) {
				Map<String,String> sSelector = new HashMap<String, String>();
				sSelector.put("code", sJson.get("fieldFullPath"));
				sSelector.put("name", sJson.get("fieldFullPath"));
				sSelectorList.add(sSelector);
			}
		}
		
		QueryWrapper<PlApiMappingStructure> qw = new QueryWrapper<PlApiMappingStructure>();
		qw.eq("api_mapping_id", dto.getApiMappingId());
		List<PlApiMappingStructure> structureList =  baseMapper.selectList(qw);
		boolean existsNewNode = false;
		if(structureList.size() > 0) {
			//报文映射已存在，对比新的报文模板，将不存在得节点写入
			List<Map<String, String>> tJsonList = FastJsonUtils.getFormatJSON(tapi.getApiRequestTemplate());
			for(Map<String,String> tJson:tJsonList) {
				String fieldFullPath = tJson.get("fieldFullPath");
				Optional<PlApiMappingStructure> fullPathOptional = structureList.stream().filter(s->fieldFullPath.equals(s.getFieldFullPath())).findAny();
				//如果该节点不存在，则将该节点新增到结构表中
				if(!fullPathOptional.isPresent()) {
					if("root".equals(fieldFullPath)) {
						continue;
					}
					PlApiMappingStructure newNode = new PlApiMappingStructure();
					newNode.setFieldFullPath(fieldFullPath);
					newNode.setApiMappingId(dto.getApiMappingId());
					newNode.setTargetFieldPath(fieldFullPath.replace("root.", ""));
					List<String> fieldFullPathList = Arrays.asList(fieldFullPath.split("\\."));
					newNode.setTargetFieldName(fieldFullPathList.get(fieldFullPathList.size()-1));
					String parentFullPath = fieldFullPath.replaceAll("."+fieldFullPathList.get(fieldFullPathList.size()-1)+"$", "");
//					String parentFullPath = fieldFullPathList.stream().collect(Collectors.joining("."));
					Long parentCode = 0l;
					if("root".equals(parentFullPath)) {
						parentCode = 0l;
					}else {
						Optional<PlApiMappingStructure> parentNode = structureList.stream().filter(s->parentFullPath.equals(s.getFieldFullPath())).findFirst();
						if(parentNode.isPresent()) {
							parentCode = parentNode.get().getTargetFieldCode();
						}
					}
					newNode.setTargetParentField(parentCode);
					
					//判断是否为报文节点
					handleIsfiledrequest(newNode,activeTarget);
					
					baseMapper.insert(newNode);
					existsNewNode = true;
				}
			}
			
			if(existsNewNode) {
				structureList =  baseMapper.selectList(qw).stream().filter(temp->"true".equals(temp.getIsfiledrequest())).collect(Collectors.toList());
			}
			List<PlApiMappingStructureDTO> tempStructureList = new ArrayList<PlApiMappingStructureDTO>();
			for(PlApiMappingStructure structure:structureList) {
				PlApiMappingStructureDTO tempDTO = new PlApiMappingStructureDTO();
				BeanUtils.copyProperties(structure, tempDTO);
				tempDTO.setSourceField(structure.getSourceFieldPath());
				tempStructureList.add(tempDTO);
			}
			
			List<PlApiMappingStructureDTO> targetStructureList = tempStructureList.stream().
																	filter(temp->
																			"true".equals(temp.getIsfiledrequest())&&
																			(!Arrays.asList("array,object".split(",")).contains(temp.getTargetFieldType()))
																			).
																	collect(Collectors.toList());
			res.put("targetStructureList", targetStructureList);
			res.put("sourceSelecter", sSelectorList);
		}else {
			//首次新增时
			List<Map<String, String>> tJsonList = FastJsonUtils.getFormatJSON(tapi.getApiRequestTemplate());
			//首次生成时候 目标api和源api若相同，将目标api报文字段填充
			if(sApi == tApi) {
				for(Map<String, String> targert:tJsonList) {
					String fieldFullPath = targert.get("fieldFullPath");
					targert.put("sourceField", fieldFullPath);
				}
			}
			res.put("targetStructureList", tJsonList);
			res.put("sourceSelecter", sSelectorList);
		}
		
		
		return res;
	}
	
	//判断是否为报文节点
	private void handleIsfiledrequest(PlApiMappingStructure node,String activeTarget) {
		if("table".equals(activeTarget)) {
			node.setIsfiledrequest("false");
		}else {
			node.setIsfiledrequest("true");
		}
	}
	
	private String getTargetTemplateForMysql(PlApibaseinfo tapi) {
		Map<String,Object> targetObject = new HashMap<String, Object>();
		String tableConfigStr = tapi.getTableConfig();
		com.alibaba.fastjson.JSONObject tableConfig = JSON.parseObject(tableConfigStr);
		String mTableName = tableConfig.getString("maintable");
		String subTableName = tableConfig.getString("subtable");
		
		String mSql = "show COLUMNS from "+mTableName;
		List<Map<String,String>> mainList = baseMapper.queryTableColums(mSql);
		for(Map<String,String> map:mainList) {
			targetObject.put(map.get("Field").toLowerCase(), "");
		}
		
		if(StringUtils.hasLength(subTableName)) {
			List<Map<String,Object>> details =new ArrayList<Map<String,Object>>();
			Map<String,Object> targetDetailObject = new HashMap<String, Object>();
			String subSql = "show COLUMNS from "+subTableName;
			List<Map<String,String>> subList = baseMapper.queryTableColums(subSql);
			for(Map<String,String> map:subList) {
				targetDetailObject.put(map.get("Field").toLowerCase(), "");
			}
			details.add(targetDetailObject);
			targetObject.put("details", details);
		}
		return JSON.toJSONString(targetObject);
	}
	



	/**
	 * 生成导出excel
	 */
	@Override
	public XSSFWorkbook downLoadExcel(PlApiMappingStructureDTO dto) {
		Map<String,Object> res = new HashMap<String, Object>();
		PlApiMapping mappingPo = plApiMappingMapper.selectById(dto.getApiMappingId());
		long sApi = mappingPo.getSourceApiId();
		long tApi = mappingPo.getTargetApiId();
		PlApibaseinfo sapi = plApibaseinfoMapper.selectById(sApi);
		PlApibaseinfo tapi = plApibaseinfoMapper.selectById(tApi);
		
		res.put("sTemplate", sapi.getApiRequestTemplate());
		res.put("tTemplate", tapi.getApiRequestTemplate());
		
		//查询已存在的字段配置
		QueryWrapper<PlApiMappingStructure> qw = new QueryWrapper<PlApiMappingStructure>();
		qw.eq("api_mapping_id", dto.getApiMappingId());
		List<PlApiMappingStructure> structureList =  baseMapper.selectList(qw);
		
		
		XSSFWorkbook workBook = new XSSFWorkbook();
		XSSFSheet sheet = workBook.createSheet("字段映射配置");
		XSSFRow row =  sheet.createRow(0);
		
		
		sheet.setColumnHidden(0, true);
		sheet.setColumnHidden(1, true);
		sheet.setColumnHidden(2, true);
		sheet.setColumnHidden(3, true);
		sheet.setColumnHidden(4, true);
		
		row.createCell(0).setCellValue("apiMappingId");
		row.createCell(1).setCellValue("companyId");
		row.createCell(2).setCellValue("id");
		row.createCell(3).setCellValue("targetFieldCode");
		row.createCell(4).setCellValue("targetFieldName");
		row.createCell(4).setCellValue("targetFieldPath");
		row.createCell(5).setCellValue("目标字段名称");
		row.createCell(6).setCellValue("源报文字段名称");
		row.createCell(7).setCellValue("是否为空");
		
		if(structureList.size() > 0) {
			int index = 1;
			for(PlApiMappingStructure structure:structureList) {
				XSSFRow structureRow =  sheet.createRow(index);
				structureRow.createCell(0).setCellValue(dto.getApiMappingId()+"");
				structureRow.createCell(1).setCellValue(dto.getCompanyId()+"");
				structureRow.createCell(2).setCellValue(structure.getId()+"");
				structureRow.createCell(3).setCellValue(structure.getTargetFieldCode()+"");
				structureRow.createCell(4).setCellValue(structure.getTargetFieldName()+"");
				structureRow.createCell(5).setCellValue(structure.getFieldFullPath()+"");
				structureRow.createCell(6).setCellValue(structure.getSourceFieldPath()+"");
				String checknull = "";
				if("true".equals(structure.getChecknull())) {
					checknull ="是";
				}else if("false".equals(structure.getChecknull())) {
					checknull ="fou";
				}else {
					checknull ="";
				}
				structureRow.createCell(7).setCellValue(checknull);
				index++;
			}
			
		}else {
			int index = 1;
			List<Map<String, String>> tJsonList = FastJsonUtils.getFormatJSON(tapi.getApiRequestTemplate());
			for(Map<String,String> temp:tJsonList) {
				XSSFRow structureRow =  sheet.createRow(index);
				structureRow.createCell(0).setCellValue(dto.getApiMappingId()+"");
				structureRow.createCell(1).setCellValue(dto.getCompanyId()+"");
				structureRow.createCell(2).setCellValue("");
				structureRow.createCell(3).setCellValue(temp.get("targetFieldCode"));
				structureRow.createCell(4).setCellValue(temp.get("fieldFullPath"));
				structureRow.createCell(5).setCellValue(temp.get("fieldFullPath"));
				index++;
			}
		}
		
		List<Map<String, String>> sJsonList = FastJsonUtils.getFormatJSON(sapi.getApiRequestTemplate());
		String[] selector = new String[sJsonList.size()];
		int index = 0;
		for(Map<String,String> sJson:sJsonList) {
			if(!StringUtils.hasLength(sJson.get("fieldType"))) {
				selector[index] = sJson.get("fieldFullPath").replace("root.", "");
			}
			index++;
		}
		String[] ischeck = {"是","否"};
		
		//设置下拉框
		setDropDownBox(workBook,"sourceSelect","字段映射配置",selector,6,6);
		setDropDownBox(workBook,"ischeckSelect","字段映射配置",ischeck,7,7);

		return workBook;
	}
	
	
	
	
	@Override
	public void uploadExcel(MultipartFile multipartFile) {
		try {
			Subject subject = SecurityUtils.getSubject();
			Session session = subject.getSession();
			String companyIdDefault = (String) Optional.ofNullable(session.getAttribute("companyid")).orElse("1");

			XSSFWorkbook workBook = new XSSFWorkbook(multipartFile.getInputStream());
			XSSFSheet sheet = workBook.getSheet("字段映射配置");
			Map<String,Integer> headerMapping = headMapping(sheet);
			int index = sheet.getLastRowNum();
			String apimappingid = null;

			for(int i=1;i<index+1;i++) {
				XSSFRow row = sheet.getRow(i);
				apimappingid = getCellValueByMappingIndex(row,headerMapping,"apiMappingId");
				Optional.ofNullable(null);
				String companyId = getCellValueByMappingIndex(row,headerMapping,"companyId");
				if("null".equals(companyId)||"".equals(companyId)) {
					companyId = companyIdDefault;
				}
				String id = getCellValueByMappingIndex(row,headerMapping,"id");
				String targetFieldCode = getCellValueByMappingIndex(row,headerMapping,"targetFieldCode");
				String fieldFullPath = getCellValueByMappingIndex(row,headerMapping,"目标字段名称");
				String sFidldPath = getCellValueByMappingIndex(row,headerMapping,"源报文字段名称");
				String checkNull = getCellValueByMappingIndex(row,headerMapping,"是否为空");

				QueryWrapper<PlApiMappingStructure> qws = new QueryWrapper<PlApiMappingStructure>();
				qws.eq("api_mapping_id", apimappingid);
				qws.eq("id", id);
				Boolean exists = baseMapper.exists(qws);
				if(exists) {
					PlApiMappingStructure po =	baseMapper.selectOne(qws);
					po.setTargetFieldPath(fieldFullPath.replaceAll("root.", ""));
					po.setTargetFieldCode(Long.parseLong(targetFieldCode));
					po.setFieldFullPath(fieldFullPath);
					String sourceField = Optional.ofNullable(sFidldPath).orElse("");
					String[] sourceFieldArray = sourceField.split("\\.");
					po.setSourceFieldName(sourceFieldArray[sourceFieldArray.length-1]);
					po.setChecknull(checkNull);
					po.setSourceFieldPath(sourceField.replace("root.", ""));

					baseMapper.update(po, qws);
				}else {
					PlApiMappingStructure po = new PlApiMappingStructure();

					po.setTargetFieldPath(fieldFullPath.replaceAll("root.", ""));
					po.setTargetFieldCode(Long.parseLong(targetFieldCode));
					po.setFieldFullPath(fieldFullPath);
					String sourceField = Optional.ofNullable(sFidldPath).orElse("");
					String[] sourceFieldArray = sourceField.split("\\.");
					po.setSourceFieldName(sourceFieldArray[sourceFieldArray.length-1]);
					po.setChecknull(checkNull);
					po.setSourceFieldPath(sourceField.replace("root.", ""));
					po.setApiMappingId(Long.parseLong(apimappingid));
					po.setCompanyId(Long.parseLong(companyId));
					baseMapper.insert(po);
				}


			}

		} catch (Exception e) {
			log.error("解析上传excel异常",e);
			throw new RuntimeException(e.getMessage());
		}


	}
	
	/**
	 * excel 映射标头字段
	 * @param sheet
	 * @return
	 */
	Map<String,Integer> headMapping(XSSFSheet sheet){
		Map<String,Integer> map = new HashMap<String, Integer>();
		int index = sheet.getRow(0).getLastCellNum();
		for(int i=0;i<index;i++) {
			XSSFCell cell =sheet.getRow(0).getCell(i);
			map.put(cell.getStringCellValue(), i);
		}
		return map;
	}
	
	/**
	 * 获取值
	 * @param row
	 * @param mapping
	 * @param mappname
	 * @return
	 */
	String getCellValueByMappingIndex(XSSFRow row,Map<String,Integer> mapping,String mappname){
		String value ="";
		XSSFCell cell = row.getCell(mapping.get(mappname));
		if(cell != null) {
			value = cell.getStringCellValue();
		}
		return value;
	}


	/**
	 * 设置下拉框数据
	 *
	 * @param wb       表格对象
	 * @param typeName 要渲染的sheet名称
	 * @param values   下拉框的值
	 * @param firstCol 起始列号
	 * @param lastCol  终止列号
	 */
	public void setDropDownBox(XSSFWorkbook wb,String hiddenSheetName, String typeName, String[] values, Integer firstCol, Integer lastCol) {
	    //获取所有sheet页个数
	    int sheetTotal = wb.getNumberOfSheets();
	    //处理下拉数据
	    if (values != null && values.length != 0) {
	        //新建一个sheet页
//	        String hiddenSheetName = "hiddenSheet";
	        XSSFSheet hiddenSheet = wb.getSheet(hiddenSheetName);
	        if (hiddenSheet == null) {
	            hiddenSheet = wb.createSheet(hiddenSheetName);
	            //写入下拉数据到新的sheet页中
	            for (int i = 0; i < values.length; i++) {
	                XSSFRow row = hiddenSheet.createRow(i);
	                XSSFCell cell = row.createCell(0);
	                cell.setCellValue(values[i]);
	            }
	            //将新建的sheet页隐藏掉
	            wb.setSheetHidden(sheetTotal, true);
	        }
	        //获取新sheet页内容
	        String strFormula = hiddenSheetName + "!$A$1:$A$65535";
	        XSSFDataValidationConstraint constraint = new XSSFDataValidationConstraint(DataValidationConstraint.ValidationType.LIST, strFormula);
	        // 设置数据有效性加载在哪个单元格上,四个参数分别是：起始行、终止行、起始列、终止列
	        CellRangeAddressList regions = new CellRangeAddressList(0, 65535, firstCol, lastCol);
	        // 数据有效性对象
	        DataValidationHelper help = new XSSFDataValidationHelper(hiddenSheet);
	        DataValidation validation = help.createValidation(constraint, regions);
	        XSSFSheet sheet1 = wb.getSheet(typeName);
	        sheet1.addValidationData(validation);
	    }

	}



	@Override
	public Map<String, Object> selectApi(PlApiMappingDTO dto) {
		// 校验请求参数
		checkSelectApiDTO(dto);
		
		PlApibaseinfo sapi = plApibaseinfoMapper.selectById(dto.getSourceApiId());
		PlApibaseinfo tapi = plApibaseinfoMapper.selectById(dto.getTargetApiId());
		
		Map<String,Object> res = new HashMap<String, Object>();
		
		res.put("sTemplate", sapi.getApiRequestTemplate());
		res.put("tTemplate", tapi.getApiRequestTemplate());
		
		List<Map<String,String>> sSelectorList = new ArrayList<Map<String,String>>();
		List<Map<String, String>> sJsonList = FastJsonUtils.getFormatJSON(sapi.getApiRequestTemplate());
		for(Map<String,String> sJson:sJsonList) {
			if(!StringUtils.hasLength(sJson.get("fieldType"))) {
				Map<String,String> sSelector = new HashMap<String, String>();
				sSelector.put("code", sJson.get("fieldCode"));
				sSelector.put("name", sJson.get("fieldFullPath"));
				sSelectorList.add(sSelector);
			}
		}
		
		List<Map<String, String>> tJsonList = FastJsonUtils.getFormatJSON(tapi.getApiRequestTemplate());
		res.put("targetStructureList", tJsonList);
		res.put("sourceSelecter", sSelectorList);
		return res;
	}
	
	private void checkSelectApiDTO(PlApiMappingDTO dto) {
		Assert.notNull(dto.getSourceApiId(),"源api_id不能为空");
		Assert.notNull(dto.getTargetApiId(),"目标api_id不能为空");
	}




	@Override
	public List<PlApiMappingStructure> queryStructureByMappingId(PlApiMappingStructureDTO dto) {
		QueryWrapper<PlApiMappingStructure> qw = new QueryWrapper<PlApiMappingStructure>();
		qw.eq("api_mapping_id", dto.getApiMappingId());
		return baseMapper.selectList(qw);
	}


	@Override
	public void addStructure(PlApiMappingStructureDTO dto) {
		QueryWrapper<PlApiMappingStructure> qw = new QueryWrapper<PlApiMappingStructure>();
		qw.eq("api_mapping_id", dto.getApiMappingId());
		List<PlApiMappingStructure> structureList =  baseMapper.selectList(qw);
		
		checkNewStructureNode(dto,structureList);
		
		PlApiMappingStructure po = new PlApiMappingStructure();
		BeanUtils.copyProperties(dto, po);
		baseMapper.insert(po);
	}
	
	//检查新增节点字段值是否符合条件
	private void checkNewStructureNode(PlApiMappingStructureDTO dto,List<PlApiMappingStructure> oriStructureList ) {
		if("root".equals(dto.getTargetFieldName())) {
			if(oriStructureList.size()>0) {
				throw new RuntimeException("root节点已存在");
			}
		}
	}


	@Override
	public void delStructureNodeAndChild(PlApiMappingStructureDTO dto) {
		LambdaQueryWrapper<PlApiMappingStructure> qw = Wrappers.lambdaQuery();
		qw.eq(PlApiMappingStructure::getApiMappingId, dto.getApiMappingId());
//		QueryWrapper<PlApiMappingStructure> qw = new QueryWrapper<PlApiMappingStructure>();
//		qw.eq("id", dto.getId());
		List<PlApiMappingStructure> structureList =  baseMapper.selectList(qw);
		List<PlApiMappingStructure> delList = new ArrayList<PlApiMappingStructure>();
		List<PlApiMappingStructure> tempList = structureList.stream().filter(temp->temp.getId().longValue()==dto.getId().longValue()).collect(Collectors.toList());
		delList.addAll(tempList);
		
		queryByParentId(dto.getTargetFieldCode(),structureList,delList);
		
        List<Long> ids = delList.stream().map(p -> p.getId()).distinct().collect(Collectors.toList());
        if(ids.size()>0) {
        	baseMapper.deleteBatchIds(ids);
        }
	}
	
	void queryByParentId(Long parentId,List<PlApiMappingStructure> structureList,List<PlApiMappingStructure> delList) {
		if(parentId == null) {
			return;
		}
		List<PlApiMappingStructure> filterList = structureList.stream().filter(temp->null != temp.getTargetParentField()).filter(temp->temp.getTargetParentField().longValue()==parentId.longValue()).collect(Collectors.toList());
		if(filterList.size()>0) {
			delList.addAll(filterList);
			for(PlApiMappingStructure tmep:filterList) {
				queryByParentId(tmep.getTargetFieldCode(),structureList,delList);
			}
		}
	};
	
	
	public void editStructure(PlApiMappingStructureDTO dto) {
		PlApiMappingStructure po = new PlApiMappingStructure();
		BeanUtils.copyProperties(dto, po);
		
		if(StringUtils.hasLength(dto.getSourceFieldName())) {
			String sourceField = Optional.ofNullable(dto.getSourceFieldName()).orElse("");
			String fieldFullPath = Optional.ofNullable(dto.getFieldFullPath()).orElse("");
			String[] sourceFieldArray = sourceField.split("\\.");
			po.setTargetFieldPath(fieldFullPath.replace("root.", ""));
			po.setSourceFieldPath(sourceField.replace("root.", ""));
			po.setSourceFieldName(sourceFieldArray[sourceFieldArray.length-1]);
		}

		
		baseMapper.updateById(po);
	}




	@Override
	public void selectStructurePage(Page<PlApiMappingStructure> pageParam, PlApiMappingStructureDTO dto) {
		LambdaQueryWrapper<PlApiMappingStructure> query = Wrappers.lambdaQuery();
        query.orderByAsc(PlApiMappingStructure::getId); 
        query.eq(PlApiMappingStructure::getApiMappingId, dto.getApiMappingId());
        String sourceFiledName = dto.getSourceFieldName();
        if("notnull".equals(sourceFiledName)) {
        	query.isNotNull(PlApiMappingStructure::getSourceFieldName);
        }else {
            if(StringUtils.hasLength(dto.getTargetFieldName())) {
            	query.like(PlApiMappingStructure::getTargetFieldName, dto.getTargetFieldName());
            }
            if(StringUtils.hasLength(dto.getMappingGloableField())) {
            	query.like(PlApiMappingStructure::getMappingGloableField, dto.getMappingGloableField());
            }
            if(StringUtils.hasLength(dto.getSourceFieldName())) {
            	query.like(PlApiMappingStructure::getSourceFieldName, dto.getSourceFieldName());
            }
            if(StringUtils.hasLength(dto.getTargetDefaultValue())) {
            	query.like(PlApiMappingStructure::getTargetDefaultValue, dto.getTargetDefaultValue());
            }
            if(StringUtils.hasLength(dto.getTargetFieldType())) {
            	query.like(PlApiMappingStructure::getTargetFieldType, dto.getTargetFieldType());
            }
            if(StringUtils.hasLength(dto.getTargetFieldPath())) {
            	query.like(PlApiMappingStructure::getTargetFieldPath,dto.getTargetFieldPath());
            }
            if(StringUtils.hasLength(dto.getIsfiledrequest())) {
            	query.like(PlApiMappingStructure::getIsfiledrequest,dto.getIsfiledrequest());
            }
            if(StringUtils.hasLength(dto.getFielddesc())) {
            	query.like(PlApiMappingStructure::getFielddesc,dto.getFielddesc());
            }
            if(StringUtils.hasLength(dto.getFieldFullPath())) {
            	query.like(PlApiMappingStructure::getFieldFullPath,dto.getFieldFullPath());
            }
        }
        baseMapper.selectPage(pageParam,query);
	}
	
	@Override
	public List<Map<String,String>> querySourceField(PlApiMappingDTO dto) {
		PlApiMapping plApiMapping = plApiMappingMapper.selectById(dto.getId());
		PlApibaseinfo sapi =	plApibaseinfoMapper.selectById(plApiMapping.getSourceApiId());
		
		List<Map<String,String>> sSelectorList = new ArrayList<Map<String,String>>();
		List<Map<String, String>> sJsonList = FastJsonUtils.getFormatJSON(sapi.getApiRequestTemplate());
		for(Map<String,String> sJson:sJsonList) {
			if(!StringUtils.hasLength(sJson.get("fieldType"))) {
				Map<String,String> sSelector = new HashMap<String, String>();
				sSelector.put("label", sJson.get("fieldFullPath"));
				sSelector.put("value", sJson.get("fieldFullPath"));
				sSelectorList.add(sSelector);
			}
		}
		return sSelectorList;
	}

	
	@Override
	public void deleteApiMappingStructureByMappingid(PlApiMappingDTO dto) {
		if(null != dto.getId()) {
			baseMapper.delStructureByApiMappingId(dto.getId());
		}
	}
}
